<?php

namespace app\controllers\api;

use app\models\Material;
use app\models\Member;
use app\models\News;
use app\models\Product;
use app\models\ProductMaterial;
use app\models\User;
use app\models\UserMaterial;
use app\models\UserProduct;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class ProductController extends BaseController {
    // 产品记录
    public function actionList($name = '', $is_material = null, $status = null) {
        $user = $this->check();
        $models = Product::find()
            ->andFilterWhere([
                'name' => $name,
                'user_id' => $user->id,
                'is_material' => $is_material,
                'status' => $status,
            ])
            ->all();
        $data = [];
        foreach ($models as $model) {
            $userProduct = $model->getUserProducts()->andWhere(['user_id'=>$user->id])->one();
            $data[] = $model->toArray() + [
                    'userProduct' => $userProduct ? $userProduct->toArray([
                        'id',
                        'num',
                        'buy_price',
                        'sale_price',
                    ]): null,
                ];
        }
        $this->log('原料 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $data,
        ]);
    }

    // 设计产品
    public function actionDesign() {
        $user = $this->check([User::ROLE_PRODUCER, ]);
        $this->checkModify();
        $post = Yii::$app->request->post();
        $model = new Product();
        $model->user_id = $user->id;
        $model->loadBeforeFilter($post, ['name', 'designer_id', 'description', 'appendix', ]);
        $model->material_cost = 0;
        if(!$model->name) {
            throw new UserException('产品名称未填写');
        }
        if(!$model->designer_id) {
            throw new UserException('未选择设计师');
        }


        /** @var ProductMaterial[] $materials */
        $materials = [];
        /** @var UserMaterial|UserProduct[] $userMaterials */
        $userMaterials = [];
        foreach ($post['formula'] as $item) {
            $material = new ProductMaterial();
            $material->loadBeforeFilter($item, ['type', 'entry_id', 'num', ]);
            if($material->num <= 0) continue;
            if(!$material->entry) {
                throw new UserException('商品不存在');
            }
            if($material->type == ProductMaterial::TYPE_MATERIAL) {
                // 原料
//                $model->material_cost += $material->num + $material->entry->price;
                $model->material_cost += $material->entry->price;
                $userMaterials[] = $userMaterial = UserMaterial::findOne([
                    'material_id' => $material->entry->id,
                    'user_id' => $user->id,
                ]);
                $userMaterial->storage_num -= $material->num;
                if($userMaterial->storage_num <0) throw new UserException('库存不足');
            } else {
                // 产品
                $model->material_cost += $material->num * $material->entry->material_cost;
                $userMaterials[] = $userMaterial = UserProduct::findOne([
                    'product_id' => $material->entry->id,
                    'user_id' => $user->id,
                ]);
                $userMaterial->num -= $material->num;
                if($userMaterial->num <0) throw new UserException('库存不足');
            }
            $materials[] = $material;
        }
        if(count($materials) == 0) {
            throw new UserException('未选择商品');
        }

        // 判断是不是原料产品
        if(count($materials) == 1 && $materials[0]->type == ProductMaterial::TYPE_MATERIAL && $materials[0]->num == 1) {
            $model->is_material = true;
            $model->status = Product::STATUS_AUTH;
            $model->pass_time = '第X财年';
            $model->govern_opinion = '-';
        } else {
            $model->is_material = false;
            $model->status = Product::STATUS_CREATE;
            $model->pass_time = '';
            $model->govern_opinion = '-';
        }


        $this->transaction(function() use ($model, $materials, $userMaterials) {
            $model->save();
            foreach ($materials as $material) {
                $material->product_id = $model->id;

                $material->save();
            }

            if(!$model->is_material) {
                foreach ($userMaterials as $userMaterial) {
                    $userMaterial->save();
                }
            }
            $this->log('产品 - 设计产品', $model->id);
        });
        return $this->renderSuccess([]);
    }

    // 生产产品
    public function actionProduct() {
        $user = $this->check([User::ROLE_PRODUCER, ]);
        $this->checkModify();
        $product_id = Yii::$app->request->post('product_id');
        /** @var Product $product */
        $product = Product::findOne($product_id);
        if(!$product || $product->user_id != $user->id) {
            throw new UserException('选择产品不存在');
        }
        /** @var UserProduct $userProduct */
        $userProduct = UserProduct::getByProduct($product, $user);
        $member_id = (int)Yii::$app->request->post('member_id');
        /** @var Member $member */
        $member = Member::findOne($member_id);
        if(!$member || $member->user_id != $user->id) {
            throw new UserException('选择的企业成员不存在');
        }

        $num = (double)Yii::$app->request->post('num');
        $price = (double)Yii::$app->request->post('price');
        if($num<=0) {
            throw new UserException('生产数量错误');
        }
        if($price<=0) {
            throw new UserException('定价错误');
        }

        $userMaterials = [];
        foreach ($product->productMaterials as $material) {
            if($material->type == ProductMaterial::TYPE_MATERIAL) {
                $userMaterials[] = $userMaterial = UserMaterial::findOne([
                    'material_id' => $material->entry->id,
                    'user_id' => $user->id,
                ]);
                if(!$userMaterial) throw new UserException('库存不足');
                $userMaterial->storage_num -= $material->num * $num;
                if($userMaterial->storage_num <0) throw new UserException('库存不足');
            } else {
                $userMaterials[] = $userMaterial = UserProduct::findOne([
                    'product_id' => $material->entry->id,
                    'user_id' => $user->id,
                ]);
                if(!$userMaterial) throw new UserException('库存不足');
                $userMaterial->num -= $material->num * $num;
                if($userMaterial->num <0) throw new UserException('库存不足');
            }
        }

        $this->transaction(function() use (&$num, $price, $userProduct, $user, $userMaterials, $member) {
            $num = round($num * (0.8 + 0.2 * min($user->tech_level,1)));
            $userProduct->num += $num;
            $userProduct->buy_price = 0;
            $userProduct->sale_price = round($price, 2);
            $userProduct->save();

            // 修改库存
            foreach ($userMaterials as $userMaterial) {
                $userMaterial->save();
            }

            // 记录提成
            $member->commission = round($member->commission + $userProduct->product->material_cost * $num * 0.03, 2);
            $member->save();
            $this->log('员工 - 生产提成', $userProduct->id);

            $this->log('产品 - 生产', $userProduct->id);
        });
        return $this->renderSuccess([
            'num' => $num,
            'userProduct' => $userProduct,
        ]);
    }

    // 产品审核
    public function actionAuth() {
        $user = $this->check([User::ROLE_GOV, ]);
        $this->checkModify();
        $product_id = Yii::$app->request->post('id');
        /** @var Product $product */
        $product = Product::findOne($product_id);
        if(!$product || $product->user->country_id != $user->country_id) {
            throw new UserException('选择产品不存在');
        }

        $this->transaction(function() use($product) {
            $product->status = Yii::$app->request->post('pass')==1 ? Product::STATUS_AUTH : Product::STATUS_REJECT;
            $product->govern_opinion = Yii::$app->request->post('govern_opinion');
            if(!$product->govern_opinion) {
                throw new UserException('审核意见不能为空');
            }

            $product->designer->commission += $product->material_cost;
            $this->log('产品审核-通过', '',-$product->material_cost*2);
            $this->logForUser($product->user,'产品审核-通过','',$product->material_cost*2);
            $product->save();
            $product->designer->save();

            $this->log('产品 - 审核', $product->id);
        });
        return $this->renderSuccess([]);
    }

    // 定价产品
    public function actionPrice() {
        $user = $this->check();
        $this->checkModify();
        $product_id = Yii::$app->request->post('product_id');
        /** @var Product $product */
        $product = Product::findOne($product_id);
        /** @var UserProduct $userProduct */
        $userProduct = UserProduct::getByProduct($product, $user);
        if(!$product || $userProduct->user_id != $user->id) {
            throw new UserException('选择产品不存在');
        }

        $price = (double)Yii::$app->request->post('price');
        if($price<=0) {
            throw new UserException('定价错误');
        }

        $this->transaction(function() use ($price, $userProduct, $user) {
            $userProduct->sale_price = round($price, 2);
            $userProduct->save();
        });

        $this->log('产品 - 定价', $userProduct->id);
        return $this->renderSuccess([
            'userProduct' => $userProduct,
        ]);
    }

    // 拥有的产品记录
    public function actionUserList($name = '', $is_material = null, $status = null) {
        $user = $this->check();
        $models = UserProduct::find()
            ->leftJoin(Product::tableName(), ['user_product.product_id'=>'product.id'])
            ->andFilterWhere([
                'name' => $name,
                'is_material' => $is_material,
                'status' => $status,
            ])
            ->andWhere([
                'user_product.user_id' => $user->id,
            ])
            ->all();
        $this->log('产品 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }

    // 拥有的产品详情
    public function actionUserDetail($id) {
        $user = $this->check();

        $model = UserProduct::findOne($id);
        if(!$model) {
            throw new UserException('信息不存在');
        }
        $this->log('产品 - 查询详情', '');
        return $this->renderSuccess([
            'model' => $model,
        ]);
    }
}
